"""A module holding python classes for various SQL tables."""

import datetime
import os

from sqlalchemy import *
from sqlalchemy.orm import sessionmaker, relation, backref
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

def SessionMaker(file_name):
  engine = create_engine("sqlite:///%s" % file_name, connect_args={"timeout" : 60.0})
  Base.metadata.create_all(engine)
  return sessionmaker(bind = engine)

class User(Base):
  """A class to hold information about a specific user."""

  __tablename__ = "users"

  # Columns:
  id = Column(Integer, primary_key = True)
  firstname = Column(String)
  lastname = Column(String)
  username = Column(String, unique = True)
  email = Column(String, unique = True)
  password = Column(String)
  is_admin = Column(Boolean, default = False)
  status = Column(Integer, default = 0)
  join_date = Column(DateTime, default = datetime.datetime.now)

  # Back References:
  # "players" which points to player instances.

class Player(Base):
  """A class to hold information about a specific player."""

  __tablename__ = "players"

  # Columns:
  id = Column(Integer, primary_key = True)
  owner_id = Column(Integer, ForeignKey("users.id"))
  version = Column(Integer)
  name = Column(String)
  rank = Column(Float)
  enabled = Column(Boolean)
  status = Column(Integer, default = 0)
  status_message = Column(String, default = "")
  date_added = Column(DateTime, default = datetime.datetime.now)
  games_won = Column(Integer, default = 0)
  games_lost = Column(Integer, default = 0)
  games_tied = Column(Integer, default = 0)
  file_name = Column(String)
  file_data = Column(Binary)
  player_class_name = Column(String, default = "")

  # Relations:
  owner = relation(User, backref = backref("players", order_by = id))

  def DiskFileName(self):
    return "%s_%s_%d" % (self.owner.username,
                         self.name,
                         self.version)

  def WriteFileToDisk(self):
    filename = "%s.py" % (self.DiskFileName())
    out_file = open(filename, "w")
    out_file.write(self.file_data)
    out_file.close()

  def RemoveFileFromDisk(self):
    filename = "%s.py" % (self.DiskFileName())
    try:
      os.remove(filename)
    except OSError:
      pass

class Game(Base):
  """A class that holds information about a single game."""

  __tablename__ = "games"

  # Columns
  id = Column(Integer, primary_key = True)
  board = Column(Binary)
  match_length = Column(Float)
  date_added = Column(DateTime, default = datetime.datetime.now)

class Score(Base):
  """A class that holds a player's score for a game."""

  __tablename__ = "scores"

  # Columns:
  id = Column(Integer, primary_key = True)
  game_id = Column(Integer, ForeignKey("games.id"))
  player_id = Column(Integer, ForeignKey("players.id"))
  score = Column(Integer)
  
  # Relations:
  game = relation(Game, backref = backref("scores"))
  player = relation(Player)

  # Back References:
  # "game" which points to the game for this object.
